import {PlusOutlined} from "@ant-design/icons";
import {Button, Divider, InputRef, Select, Space} from "antd";
import Input from "antd/es/input/Input";
import {DefaultOptionType} from "rc-select/lib/Select";
import React, {useEffect, useRef, useState} from "react";


interface CustomSelectProps {
    value?: string[] | null |undefined;
    options: DefaultOptionType[];
    onSelect: (value: string[]) => void;
    mode?: 'multiple' | 'tags'
}

const CustomSelect = (props: CustomSelectProps) => {
    const [name, setName] = useState<string>('')
    const [options, setOptions] = useState<DefaultOptionType[]>([])
    const [value, setValue] = useState<string[] | null |undefined>([])
    const inputRef = useRef<InputRef>(null)

    useEffect(() => {
        setOptions(props.options)
    }, [props.options])

    useEffect(() => {
        setValue(props.value)
    }, [props.value]);

    const onNameChange = (event: React.ChangeEvent<HTMLInputElement>) => {
        setName(event.target.value);
    };
    const addItem = (e: React.MouseEvent<HTMLButtonElement | HTMLAnchorElement>) => {
        if (name) {
            e.preventDefault();
            setOptions([...options, {
                label: name,
                value: name,
            }]);
            setName('');
            setTimeout(() => {
                inputRef.current?.focus();
            }, 0);
        }
    };
    return (
        <Select
            style={{width: 300}}
            options={options}
            onChange={(value) => {
                props.onSelect(value)
                setValue(value)
            }}
            mode={props.mode}
            placeholder={"请选择标签"}
            value={value}
            dropdownRender={(menu) => (
                <>
                    {menu}
                    <Divider style={{margin: '8px 0'}}/>
                    <Space style={{padding: '0 8px 4px'}}>
                        <Input
                            ref={inputRef}
                            placeholder="Please enter item"
                            value={name}
                            onChange={onNameChange}
                            onKeyDown={(e) => e.stopPropagation()}
                        />
                        <Button type="text" icon={<PlusOutlined/>} onClick={addItem}>
                            Add item
                        </Button>
                    </Space>
                </>
            )}
        >

        </Select>
    );
};

export default CustomSelect;
